package org.xsk.network.udp;

import java.io.IOException;
import java.net.*;

/**
 * description: 基于UDP协议的客户端
 * <p>
 * date: 2021/6/10 13:40
 * author: x-one
 */
public class LoginClient {
    public static void main(String[] args) {
        String info = "你好啊，服务器！";
        byte[] infos = info.getBytes();
        //获得一个InetAddress
        InetAddress address;
        DatagramSocket socket=null;
        try {
            address = Inet4Address.getByName("localhost");
            //建立一个包裹封装数据
            DatagramPacket dp = new DatagramPacket(infos,infos.length,address,8000);
            //建立快递点
            socket = new DatagramSocket();
            //通过快递点发送数据
            socket.send(dp);

            //接收服务器发来的信息
            //创建一个空包接收
            byte[] b = new byte[1024];
            DatagramPacket dp1 = new DatagramPacket(b, b.length);
            socket.receive(dp1);
            // 读取信息
            String reply = new String(dp1.getData(), 0, dp1.getData().length);
            System.out.println(reply);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            socket.close();
        }
    }
}
